﻿#include "StatisticsTableModel.h"

StatisticsTableModel::StatisticsTableModel(QObject *parent)
    : QAbstractTableModel(parent)
{
}

void StatisticsTableModel::setJsonData(const QJsonObject &jsonData)
{
    beginResetModel();
    m_dataArray = jsonData["data"].toArray();

    if (!m_dataArray.isEmpty() && m_dataArray[0].isObject()) {
        m_headers = m_dataArray[0].toObject().keys();
    }

    // 解析行表头
    m_rowHeaders.clear();
    QJsonArray rowHeadersArray = jsonData["rowHeaders"].toArray();
    for (const QJsonValue &value : rowHeadersArray) {
        m_rowHeaders.append(value.toString());
    }

    endResetModel();
}
void StatisticsTableModel::addRecord(const QJsonObject &newRecord)
{
    beginInsertRows(QModelIndex(), 0, 0);
    m_dataArray.prepend(newRecord);
    endInsertRows();
}
int StatisticsTableModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_dataArray.size() + 1; // 额外增加一行用于统计
}

int StatisticsTableModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_headers.size() + 1; // 额外增加一列用于统计
}

QVariant StatisticsTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= rowCount() || index.column() >= columnCount())
        return QVariant();

    if (role == Qt::DisplayRole) {
        if (index.row() < m_dataArray.size() && index.column() < m_headers.size()) {
            QJsonObject obj = m_dataArray[index.row()].toObject();
            return obj.value(m_headers[index.column()]).toVariant();
        }

        // 统计列（最后一列）
        if (index.column() == m_headers.size() && index.row() < m_dataArray.size()) {
            return calculateRowStatistics(m_dataArray[index.row()].toObject()).value("sum");
        }

        // 统计行（最后一行）
        if (index.row() == m_dataArray.size() && index.column() < m_headers.size()) {
            return calculateColumnStatistics().value(m_headers[index.column()]);
        }
    }

    return QVariant();
}

QVariant StatisticsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole) {
        if (orientation == Qt::Horizontal) {
            if (section < m_headers.size()) {
                return m_headers.value(section);
            } else {
                return "Row Sum"; // 统计列的标题
            }
        } else { // 处理行表头
            if (section < m_dataArray.size()) {
                if (!m_rowHeaders.isEmpty() && section < m_rowHeaders.size()) {
                    return m_rowHeaders[section]; // 使用 JSON 提供的行表头
                }
                return section + 1; // 默认使用行号
            } else {
                return "Column Sum"; // 统计行的标题
            }
        }
    }
    return QVariant();
}

QJsonObject StatisticsTableModel::calculateRowStatistics(const QJsonObject &rowData) const
{
    QJsonObject result;
    double sum = 0.0;
    for (const QString &key : rowData.keys()) {
        sum += rowData.value(key).toDouble();
    }
    result["sum"] = sum;
    return result;
}

QJsonObject StatisticsTableModel::calculateColumnStatistics() const
{
    QJsonObject result;
    for (const QString &key : m_headers) {
        double sum = 0.0;
        for (const QJsonValue &value : m_dataArray) {
            sum += value.toObject().value(key).toDouble();
        }
        result[key] = sum;
    }
    return result;
}
